package com.fastadmin.service;


import cn.hutool.core.exceptions.ExceptionUtil;
import com.fastadmin.mapper.impl.UserMapper;
import com.fastadmin.mapper.impl.UserRoleMapper;
import com.fastadmin.pojo.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserService {
    private final UserMapper userMapper;
    private final UserRoleMapper userRoleMapper;
    /**
     * 删除用户的时候，也得把用户对应的角色表里面授权的关系删除
     *
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(String ids) {
        userRoleMapper.deleteByUserId(Long.valueOf(ids));
        userMapper.deleteByIds(ids);

    }


    @Transactional(rollbackFor = Exception.class)
    public void reSaveUser(User user) {
        Long user_id = (Long) userMapper.saveAndGetKey(user);
        user.setId(user_id);
        //再次插入 ，肯定主键冲突
        log.info("已经插入了{}", user);
        userMapper.saveAndGetKey(user);
    }


    @Transactional(rollbackFor = Exception.class)
    public void reSaveUser2(User user) {
        try {

            Long user_id = (Long) userMapper.saveAndGetKey(user);
            user.setId(user_id);
            log.info("查询的数据2:" + userMapper.findById(user_id));
            userMapper.saveAndGetKey(user);
        } catch (Exception e) {
            log.error("发生异常,进行手动回滚！");
            // 手动回滚事物
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("{}", ExceptionUtil.stacktraceToString(e));
        }
    }
}
